package com.ruoyi.wx.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.TreeEntity;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.wx.entity.PtTeacherClass;
import com.ruoyi.wx.entity.dto.MyClassDTO;
import com.ruoyi.wx.mapper.PtTeacherClassMapper;
import com.ruoyi.wx.service.IPtTeacherClassService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 教师管理班级对应表 服务实现类
 * </p>
 *
 * @author moxiu
 * @since 2022-03-06
 */
@Service
public class PtTeacherClassServiceImpl extends ServiceImpl<PtTeacherClassMapper, PtTeacherClass> implements IPtTeacherClassService {

    @Autowired
    private SysDeptMapper sysDeptMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean chooseClass(Long teacherId, List<PtTeacherClass> list) {
        boolean remove = remove(Wrappers.lambdaQuery(PtTeacherClass.class)
            .eq(PtTeacherClass::getTeacherId, Math.toIntExact(teacherId)));
        boolean b = saveBatch(list);
        return remove && b;
    }

    @Override
    public List<MyClassDTO> getMyClass() {
        Long userId = SecurityUtils.getUserId();
        List<Long> ids = baseMapper.getMyClassId(userId);
        List<MyClassDTO> res = new ArrayList<>();
        if (ids == null || ids.size() == 0) {
            return res;
        }
        for (long id : ids) {
            res.add(new MyClassDTO(id,spliceName(id)));
        }
        return res;
    }

    public String spliceName(long deptId) {
        StringBuilder s = new StringBuilder();
        SysDept sysDeptMinByDeptId1 = getSysDeptMinByDeptId(deptId);
        SysDept sysDeptMinByDeptId2 = getSysDeptMinByDeptId(sysDeptMinByDeptId1.getParentId());
        SysDept sysDeptMinByDeptId3 = getSysDeptMinByDeptId(sysDeptMinByDeptId2.getParentId());
        SysDept sysDeptMinByDeptId = getSysDeptMinByDeptId(sysDeptMinByDeptId3.getParentId());
        s.append(sysDeptMinByDeptId.getDeptName()).append(sysDeptMinByDeptId2.getDeptName()).append(sysDeptMinByDeptId1.getDeptName());
        return s.toString();
    }

    public SysDept getSysDeptMinByDeptId(long deptId) {
        return sysDeptMapper.selectOne(Wrappers.lambdaQuery(SysDept.class).eq(SysDept::getDeptId, deptId)
            .select(SysDept::getDeptId, TreeEntity::getParentId, SysDept::getDeptName)
        );
    }
}
